<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { FormType } from './index'
import { GetDataDetail, PostCreateData, PutModifyData } from '@/api/modules/drawact'
import detailStore from '@/store/modules/cacheData'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<FormType>({
  drawBg: '',
  wheelBg: '',
  drawPrebg: '',
  newUserNums: 0,
  bgColor: '',
  btnBg: '',
  btnBgColor: '',
  ruleIcon: '',
  rulePic: '',
  myprizeBg: '',
  myprizeIcon: '',
  myprizeTicketbg: '',
  moreIcon: '',
  moreLink: '',
  productJson: [],
  getPrizeLayer: '',
  getPrizeTypeColor: '',
  getPrizeNameColor: '',
  getPrizeBtnColor: '',
  getPrizeBgbtnColor: '',
  sharePic: '',
  shareTxt: '',
  actStatus: 0,
  beginTime: '',
  endTime: '',
  drawId: '',
  descriptionTxt: '',
  descriptionPic: '',
  drawActTasks: [],
})

const drawActTasksTypeOption = [
  {
    label: '邀请好友抽奖',
    value: 1,
  },
  {
    label: '加企微',
    value: 2,
  },
  {
    label: '下单',
    value: 3,
  },
  {
    label: '邀请好友下单',
    value: 4,
  },
]
const actStatusTypeOption = [
  {
    label: '启用',
    value: 1,
  },
  {
    label: '停用',
    value: -1,
  },
]

const id = route.query.id as string

// 图片上传赋值
function handleUploadSuccess(type: string, url: string, key: string, subscript: number, name?: string) {
  if (type === 'list') {
    // eslint-disable-next-line ts/ban-ts-comment
    // @ts-expect-error
    ruleForm.value[key][subscript][name] = url
  }
  else {
    // eslint-disable-next-line ts/ban-ts-comment
    // @ts-expect-error
    ruleForm.value[key] = url
  }
}

// 添加
function AddproductJson() {
  (ruleForm.value.productJson as { pic: string, link: string }[]).push({
    link: '',
    pic: '',
  })
}
function AddDrawActTasks() {
  ruleForm.value.drawActTasks.push({
    drawTaskId: 0,
    taskType: 0,
    taskPic: '',
    taskStatus: 0,
    sendNums: 0,
    taskEveryLimit: 0,
    taskLayer: '',
    linkUrl: '',
  })
}
// 删除
function DeleteproductJson(index: number) {
  (ruleForm.value.productJson as { pic: string, link: string }[]).splice(index, 1)
}
function DeleteDrawActTasks(index: number) {
  ruleForm.value.drawActTasks.splice(index, 1)
}

function customStringify(array: any[]): string {
  return `[${array.map((obj: any) => {
    const entries = Object.entries(obj).map(([key, value]) => {
      // 处理值
      let processedValue
      if (value === null) {
        processedValue = 'null'
      }
 else if (typeof value === 'string') {
        // 转义字符串中的特殊字符
        processedValue = `'${value.replace(/'/g, '\\\'')}'`
      }
 else if (typeof value === 'object') {
        // 简单处理对象（更完善的做法是递归调用）
        processedValue = `'${JSON.stringify(value)}'`
      }
 else {
        processedValue = value
      }
      return `${key}:${processedValue}`
    })
    return `{${entries.join(',')}}`
  }).join(',')}]`
}

// 提交
async function SubmitData() {
  const params = {
    ...ruleForm.value,
  }
  // eslint-disable-next-line ts/ban-ts-comment
  // @ts-expect-error
  params.productJson = customStringify(params.productJson as any[])
  if (id) {
    // 编辑
    params.drawId = id
    PutModifyData(params).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('编辑成功')
        router.push({ name: 'drawactIndex' })
      }
    })
  }
  else {
    // 添加
    PostCreateData(params).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('添加成功')
        detailData.EmptyDrawact()
        router.push({ name: 'drawactIndex' })
      }
    })
  }
}

// const imageViewerVisible = ref(false)
// const imageViewerUrl = ref('')
// const imageViewerForm: { [key: string]: string } = {
//   drawBg: '@/assets/images/reference/背景图.png',
// }
// 预览
// function preview(key: string) {
//   imageViewerUrl.value = imageViewerForm[key]
//   console.log(imageViewerUrl.value)
//   imageViewerVisible.value = true
// }
// 关闭预览
// function previewClose() {
//   imageViewerVisible.value = false
// }
function stringToObjectArray(str: string) {
  // 1. Remove outer double quotes if they exist
  let jsonStr = str.trim()
  if (jsonStr.startsWith('"') && jsonStr.endsWith('"')) {
    jsonStr = jsonStr.slice(1, -1)
  }

  // 2. Replace property names with quoted versions
  jsonStr = jsonStr.replace(/(\w+)(\s*:)/g, '"$1"$2')

  // 3. Replace all single quotes with double quotes
  jsonStr = jsonStr.replace(/'/g, '"')

  // 4. Safer handling of URLs with question marks - now using a two-step approach
  // First handle simple cases without question marks
  // Then handle cases with question marks more carefully
  jsonStr = jsonStr.replace(/:\s*"([^"?]*)"/g, ': "$1"')
  jsonStr = jsonStr.replace(/:\s*"([^"?]*\?[^"]*)"/g, ': "$1"')

  // 5. Parse as JSON
  try {
    return JSON.parse(jsonStr)
  }
  catch (error) {
    console.error('Failed to parse JSON:', jsonStr)
    throw error
  }
}

watch(ruleForm, (newValue) => {
  detailData.RememberEnterpriseWeChat(newValue)
}, { deep: true })

onMounted(async () => {
  if (id) {
    await GetDataDetail(id).then((res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
        // console.log(ruleForm.value.productJson)

        // eslint-disable-next-line ts/ban-ts-comment
        // @ts-expect-error
        ruleForm.value.productJson = stringToObjectArray(ruleForm.value.productJson as string)
      }
    })
  }
  else {
    ruleForm.value = detailData.GetDrawactData()
  }
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :model="ruleForm">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="分享语">
              <el-input v-model="ruleForm.shareTxt" style="width: 300px;" placeholder="请输入分享语" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="活动状态">
              <el-select v-model="ruleForm.actStatus" placeholder="请选择活动状态" style="width: 300px;">
                <el-option
                  v-for="items in actStatusTypeOption" :key="items.value" :label="items.label" :value="items.value"
                />
              </el-select>
            </elformitem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="新用户赠送次数">
              <el-input v-model="ruleForm.newUserNums" style="width: 300px;" placeholder="请输入活动默认发送抽奖次数" type="number" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="活动开始时间">
              <el-date-picker
                v-model="ruleForm.beginTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="datetime"
                placeholder="请选择活动开始的日期时间"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="活动结束时间">
              <el-date-picker
                v-model="ruleForm.endTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="datetime"
                placeholder="请选择活动结束的日期时间"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="页面背景色">
              <el-color-picker v-model="ruleForm.bgColor" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="按钮文字色值">
              <el-color-picker v-model="ruleForm.btnBgColor" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="奖品按钮文字色值">
              <el-color-picker v-model="ruleForm.getPrizeBtnColor" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="奖品按钮背景色值">
              <el-color-picker v-model="ruleForm.getPrizeBgbtnColor" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="24">
            <ElFormItem label="使用说明文案">
              <el-input v-model="ruleForm.descriptionTxt" style="width: 300px;" placeholder="请输入使用说明文案" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="使用说明图">
              <div>
                <ImageUpload
                  width="auto" height="200" :size="5" :url="ruleForm.descriptionPic" :ext="['jpg', 'png']"
                  @on-success="(imgUrl: string) => handleUploadSuccess('single', imgUrl, 'descriptionPic', 0)"
                />
              </div>
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="活动背景图">
              <div>
                <ImageUpload
                  width="auto" height="200" :size="5" :url="ruleForm.drawBg" :ext="['jpg', 'png']"
                  @on-success="(imgUrl: string) => handleUploadSuccess('single', imgUrl, 'drawBg', 0)"
                />
              </div>
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="转盘图">
              <ImageUpload
                width="auto" height="200" :size="5" :url="ruleForm.wheelBg" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess('single', imgUrl, 'wheelBg', 0)"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="活动前景图">
              <ImageUpload
                width="auto" height="200" :size="5" :url="ruleForm.drawPrebg" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess('single', imgUrl, 'drawPrebg', 0)"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="抽奖按钮图">
              <ImageUpload
                width="auto" height="200" :size="5" :url="ruleForm.btnBg" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess('single', imgUrl, 'btnBg', 0)"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="规则图标">
              <ImageUpload
                width="auto" height="200" :size="5" :url="ruleForm.ruleIcon" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess('single', imgUrl, 'ruleIcon', 0)"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="规则图">
              <ImageUpload
                width="auto" height="200" :size="5" :url="ruleForm.rulePic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess('single', imgUrl, 'rulePic', 0)"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="奖品背景图">
              <ImageUpload
                width="auto" height="200" :size="5" :url="ruleForm.myprizeBg" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess('single', imgUrl, 'myprizeBg', 0)"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="奖品图标">
              <ImageUpload
                width="auto" height="200" :size="5" :url="ruleForm.myprizeIcon" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess('single', imgUrl, 'myprizeIcon', 0)"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="我的奖品券背景图">
              <ImageUpload
                width="auto" height="200" :size="5" :url="ruleForm.myprizeTicketbg" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess('single', imgUrl, 'myprizeTicketbg', 0)"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="活动分享图">
              <ImageUpload
                width="auto" height="200" :size="5" :url="ruleForm.sharePic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess('single', imgUrl, 'sharePic', 0)"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="更多抽奖机会图标">
              <ImageUpload
                width="auto" height="200" :size="5" :url="ruleForm.moreIcon" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess('single', imgUrl, 'moreIcon', 0)"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="更多抽奖机会链接">
              <el-input v-model="ruleForm.moreLink" style="width: 300px;" placeholder="请输入音乐描述" />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain title="关联商品">
        <ElRow :gutter="20">
          <ElCol :md="24">
            <ElFormItem label="操作">
              <el-button @click="AddproductJson">
                新增
              </el-button>
            </ElFormItem>
          </ElCol>
          <ElCol v-for="(item, index) in ruleForm.productJson" :key="index" :md="8" class="mb-5">
            <el-card shadow="hover">
              <el-scrollbar height="400px" :noresize="true">
                <div>
                  <ElFormItem label="链接">
                    <el-input v-model="item.link" class="max-w-xs" placeholder="请输入链接" />
                  </ElFormItem>
                  <ElFormItem label="图片">
                    <ImageUpload
                      height="200" width="auto" :size="1" :url="item.pic" :ext="['jpg', 'png']"
                      @on-success="(imgUrl: string) => handleUploadSuccess('list', imgUrl, 'productJson', index, 'pic')"
                    />
                  </ElFormItem>
                </div>
              </el-scrollbar>
              <template #footer>
                <div class="flex justify-between">
                  <el-button type="danger" @click="DeleteproductJson(index)">
                    删除
                  </el-button>
                </div>
              </template>
            </el-card>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain title="活动任务">
        <ElRow :gutter="20">
          <ElCol :md="24">
            <ElFormItem label="操作">
              <el-button @click="AddDrawActTasks">
                新增
              </el-button>
            </ElFormItem>
          </ElCol>
          <ElCol v-for="(item, index) in ruleForm.drawActTasks" :key="item.drawTaskId" :md="8" class="mb-5">
            <el-card shadow="hover">
              <el-scrollbar height="400px" :noresize="true">
                <div class="card-box">
                  <ElFormItem label="任务类型">
                    <el-select v-model="item.taskType" placeholder="请选择任务类型" class="max-w-xs">
                      <el-option
                        v-for="items in drawActTasksTypeOption" :key="items.value" :label="items.label" :value="items.value"
                      />
                    </el-select>
                  </elformitem>
                  <ElFormItem label="是否启用">
                    <el-switch
                      v-model="item.taskStatus"
                      class="ml-2"
                      :active-value="1"
                      :inactive-value="-1"
                    />
                  </elformitem>
                  <ElFormItem label="发送抽奖次数">
                    <el-input v-model="item.sendNums" class="max-w-xs" placeholder="请输入发送抽奖次数" type="number" />
                  </elformitem>
                  <ElFormItem v-if="item.taskType === 1" label="任务每日完成限制">
                    <el-input v-model="item.taskEveryLimit" class="max-w-xs" placeholder="请输入任务每日完成限制" type="number" />
                  </elformitem>
                  <ElFormItem v-if="item.taskType === 2" label="加企微弹层" class="content">
                    <!-- <el-input v-model="item.taskLayer" class="max-w-xs" placeholder="请输入加企微弹层" type="number" /> -->
                    <ImageUpload
                      height="150" width="auto" :size="5" :url="item.taskLayer" :ext="['jpg', 'png']"
                      @on-success="(imgUrl: string) => handleUploadSuccess('list', imgUrl, 'drawActTasks', index, 'taskLayer')"
                    />
                  </elformitem>
                  <ElFormItem label="任务banner图" class="content">
                    <ImageUpload
                      height="150" width="auto" :size="5" :url="item.taskPic" :ext="['jpg', 'png']"
                      @on-success="(imgUrl: string) => handleUploadSuccess('list', imgUrl, 'drawActTasks', index, 'taskPic')"
                    />
                  </ElFormItem>
                  <ElFormItem label="跳转链接">
                    <el-input v-model="item.linkUrl" style="max-width: 400px;" placeholder="请输入跳转链接" />
                  </elformitem>
                </div>
              </el-scrollbar>
              <template #footer>
                <div class="flex justify-between">
                  <el-button type="danger" @click="DeleteDrawActTasks(index)">
                    删除
                  </el-button>
                </div>
              </template>
            </el-card>
          </ElCol>
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData()">
        提交
      </ElButton>
    </FixedActionBar>
    <!-- <ElImageViewer v-if="imageViewerVisible" :url-list="[imageViewerUrl]" teleported @close="previewClose" /> -->
  </div>
</template>

<style lang="scss" scoped>
.box {
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}

.card-box {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;

  .content {
    grid-column: 1 / 3;
  }
}
</style>
